<?php
/**
 * shopify上传平台销售
 * User: bgl
 * Date: 2022/9/7
 * Time: 18:51
 */

namespace App\Admin\Controllers\Products;


use App\Importer\Basics\BImporter;
use App\Models\Basics\SysCountry;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductShopifySkuCCS;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class ShopifySkuCCSUploadController extends AdminController {

    protected $title = 'Shopify销售上传';

    protected function grid()
    {
        return view("products.shopify-sku-ccs.index");
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file){
        try{

            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            foreach($data as $row){
                $count++;
                $_country = $row[0] ? trim($row[0]) : '';
                $classify = $row[1] ? trim($row[1]) : '';
                $seller   = $row[2] ? trim($row[2]) : '';
                if(!$_country || !$classify || !$seller){
                    $errors[$count] = ',必填项为空';
                    continue;
                }

                $country = strtoupper($_country);
                $key = $country.'_'.$classify;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = ',重复记录';
                    continue;
                }
                $countryId = SysCountry::getIdByCountry($country);
                if(!$countryId){
                    $errors[$count] = '['.$_country.'],国家不存在';
                    continue;
                }
                $classifyId = ProductClassify::getIdByTitle($classify);
                if(!$classifyId){
                    $errors[$count] = '['.$classify.'],品类不存在';
                    continue;
                }
                $sellerId = User::getIdByUsername($seller);
                if(!$sellerId){
                    $errors[$count] = '['.$seller.'],销售不存在或已停用';
                    continue;
                }

                DB::beginTransaction();
                $ccs = ProductShopifySkuCCS::query()->firstOrNew([
                    'country_id' => $countryId,
                    'classify_id' => $classifyId
                ]);
                $ccs->seller_id = $sellerId;
                if($ccs->save()){
                    //更新,回写产品销售
                    ProductShopifySkuCCS::upSellerId($countryId, $classifyId, $sellerId);
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
